package com.aracky.system.controller;

import com.aracky.common.exception.BaseException;
import com.aracky.common.util.ConvertUtil;
import com.aracky.common.util.JWTUtil;
import com.aracky.common.util.UserIPUtil;
import com.aracky.common.vo.CommonResult;
import com.aracky.common.vo.LoginUserVO;
import com.aracky.system.constants.ComConstants;
import com.aracky.system.model.entity.SysRole;
import com.aracky.system.model.entity.SysUser;
import com.aracky.system.model.entity.SysUserRole;
import com.aracky.system.model.form.LoginUserForm;
import com.aracky.system.model.vo.SysUserVO;
import com.aracky.system.model.vo.view.MenuVO;
import com.aracky.system.service.SysRoleMenuService;
import com.aracky.system.service.SysRoleService;
import com.aracky.system.service.SysUserRoleService;
import com.aracky.system.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @Author zengzhiping
 * @BelongsPackage com.aracky.system.controller
 * @CreateTime 2022-07-15
 * @Description
 */
@RestController
@Api(tags = "用户登录接口")
public class LoginUserController {

    @Autowired
    private AuthenticationManager authentiactionManager;

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysUserRoleService sysUserRoleService;


    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private SysUserService sysUserService;


    @PostMapping("/login")
    @ApiOperation(value = "登录接口")
    public CommonResult logingUser(@RequestBody LoginUserForm loginUserForm) {
        //登陆-调用service
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(loginUserForm.getUserName(), loginUserForm.getPassword());
        Authentication authenticate = authentiactionManager.authenticate(usernamePasswordAuthenticationToken);

        if (Objects.isNull(authenticate)) {
            return CommonResult.error("登录失败");
        }
        //登陆成功，生成token
        LoginUserVO loginUser = (LoginUserVO) authenticate.getPrincipal();
        String jti = UUID.randomUUID().toString();
        String token = JWTUtil.createToken(loginUser, jti);

        //登录成功之后需要修改登录ip,登录时间
        sysUserService.updateLoginInfo(loginUser.getUserId());

        return CommonResult.success(token, "登录成功");
    }

    @SneakyThrows
    @GetMapping("/wx/login")
    @ApiOperation(value = "微信登录认证")
    public CommonResult wxLogin(String wxUserId)  {
        //使用微信id查询用户信息
        LambdaQueryWrapper<SysUser> userLambdaQueryWrapper =
                Wrappers.<SysUser>lambdaQuery().eq(SysUser::getWxUserId, wxUserId);
        SysUser sysUser = sysUserService.getOne(userLambdaQueryWrapper);
        //登陆
        if (Objects.isNull(sysUser)) {
            throw new BaseException("不存在当前企业微信用户");
        }
        //登陆成功，生成token
        LoginUserVO loginUser = ConvertUtil.sourceToTarget(sysUser, LoginUserVO.class);
        String jti = UUID.randomUUID().toString();
        String token = JWTUtil.createToken(loginUser, jti);
        return CommonResult.success(token,"登录成功");
    }


    @GetMapping("/currentMenuList")
    @ApiOperation(value = "查询当前登录用户菜单按钮(树形结构)")
    public CommonResult<List<MenuVO>> getMenuList() {
        Long currentUserId = UserIPUtil.getCurrentUserId();
        List<MenuVO> menuList = sysRoleMenuService.getCurrentMenuList(currentUserId,true);
        return CommonResult.success(menuList);
    }

    @GetMapping("/currentUser")
    @ApiOperation(value = "查询当前登录用户信息")
    public CommonResult<SysUserVO> getUser() {
        Long currentUserId = UserIPUtil.getCurrentUserId();
        LambdaQueryWrapper<SysUserRole> sysUserLambdaQueryWrapper=new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId,currentUserId);
        List<SysUserRole> sysUserRoleList=sysUserRoleService.list(sysUserLambdaQueryWrapper);
        List<Long> roleList=new ArrayList<>();
        for(SysUserRole sysUserRole: sysUserRoleList){
            roleList.add(sysUserRole.getRoleId());
        }

        SysUser user = sysUserService.getById(currentUserId);
        SysUserVO sysUserVO = ConvertUtil.sourceToTarget(user, SysUserVO.class);
        if (!roleList.isEmpty()){
            LambdaQueryWrapper<SysRole> lambdaQueryWrapper=new LambdaQueryWrapper<SysRole>()
                    .in(SysRole::getRoleId,roleList);
            List<SysRole> sysRoleList= sysRoleService.list(lambdaQueryWrapper);
            sysUserVO.setRoleList(sysRoleList);
        }
        //查询菜单信息
        List<MenuVO> menuList = sysRoleMenuService.getCurrentMenuList(currentUserId,false);
        List<String> buttonList = menuList.stream().filter(menuVO -> ComConstants.MENU.TYPES[2].equals(menuVO.getMenuType()))
                .map(MenuVO::getPerms)
                .collect(Collectors.toList());
        sysUserVO.setButtonList(buttonList);
        return CommonResult.success(sysUserVO);
    }


}
